package com.gxa.service.impl;

import com.gxa.common.CustomizedToken;
import com.gxa.common.LoginType;
import com.gxa.common.R;
import com.gxa.entity.DistrictSysUser;
import com.gxa.entity.SysActionLog;
import com.gxa.mapper.DistrictSysUserMapper;
import com.gxa.service.DistrictSysUserService;
import com.gxa.utils.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service
public class DistrictSysUserServiceImpl implements DistrictSysUserService {
    @Autowired
    DistrictSysUserMapper districtSysUserMapper;


    @Override
    public R login(String nickName, String password, HttpServletResponse response) {
        R r = new R();
        try {
            //得到主体
            Subject subject = SecurityUtils.getSubject();
            //获取相应的token
            CustomizedToken customizedToken = new CustomizedToken(nickName,password, LoginType.DISTRICT.toString());
            //登录
            subject.login(customizedToken);

            DistrictSysUser districtSysUser = districtSysUserMapper.findSysUserByNickname(nickName);
            SysActionLog sysActionLog = new SysActionLog();
            sysActionLog.setOrganization(districtSysUser.getOrganization());
            sysActionLog.setOperationTime(new Date());
            sysActionLog.setOperator(districtSysUser.getUserName());
            sysActionLog.setOperationContent("登录系统");
            districtSysUserMapper.addSysActionLog(sysActionLog);



            List permissionList = districtSysUserMapper.findPermissionByUserId(districtSysUser.getUserId());

            Map resultMap = new HashMap();
            resultMap.put("districtSysUser",districtSysUser);
            resultMap.put("permissionList",permissionList);


            //登录成功
            r.setCode(200);
            r.setMsg("登录成功");
            r.setData(resultMap);


            String token = JwtUtils.createJwt(UUID.randomUUID().toString(),JwtUtils.JWT_SECERT,nickName,JwtUtils.TTMILLIS);
            //通过响应头返回
            response.addHeader("Authorization",token);
            response.setHeader("Access-Control-Expose-Headers","Authorization");
        }catch (UnknownAccountException e){
            System.out.println("==账户有误==");
            r.setCode(500);
            r.setMsg("账户或密码有误");
        }catch (IncorrectCredentialsException e){
            System.out.println("==密码有误==");
            r.setCode(500);
            r.setMsg("账户或密码有误");
        }catch (LockedAccountException e){
            System.out.println("==账号被锁==");
            r.setCode(500);
            r.setMsg("账号被锁");
        }catch (AuthenticationException e){
            System.out.println("==认证错误==");
            r.setCode(500);
            r.setMsg("认证错误");
        }
        return r;
    }
}
